package com.dzl.exchange.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.WelfareExchangeEnum;
import com.dzl.exchange.dao.WelfareExchangeSecretMapper;
import com.dzl.exchange.pojo.WelfareExchangeSecret;
import com.dzl.exchange.pojo.dto.ExchangeSecretDto;
import com.dzl.exchange.pojo.query.ExchangeSecretQuery;
import com.dzl.exchange.pojo.vo.ExchangeSecretVo;
import com.dzl.exchange.pojo.vo.ExchangeUserSecretVo;
import com.dzl.exchange.pojo.vo.WelfareExchangeWithSecretVo;
import com.dzl.exchange.service.WelfareExchangeSecretService;
import com.dzl.fee.pojo.WelfareFeeOrder;
import com.dzl.fee.pojo.WelfareFeeUserCustomers;
import com.dzl.fee.pojo.WelfareFeeUserSales;
import com.dzl.fee.pojo.query.WelfareSalesCustomersQuery;
import com.dzl.fee.service.WelfareFeeOrderService;
import com.dzl.order.pojo.WelfareOrder;
import com.dzl.order.service.WelfareOrderService;
import com.dzl.util.EmptyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 兑换券信息表(WelfareExchangeSecretDetails)表服务实现类
 * @author caobucao
 * @date 2021-07-09 18:29:18
 */
@Service
public class WelfareExchangeSecretServiceImpl extends BaseServiceImpl<WelfareExchangeSecret> implements WelfareExchangeSecretService {

    @Autowired
    private WelfareExchangeSecretMapper mapper;
    @Autowired
    private WelfareFeeOrderService welfareFeeOrderService;
    @Autowired
    private WelfareOrderService welfareOrderService;


    @Override
    public PageInfo<ExchangeSecretVo> queryExchangeSecretPage(ExchangeSecretQuery query) {
       /* String queryStr = query.getQueryStr();
        if (EmptyUtils.isNotEmpty(queryStr)) {
            if (queryStr.length() == 19) {
                query.setQueryStr(queryStr.replaceAll("-", ""));
            }
        }*/
        PageHelper.startPage(query);
        List<ExchangeSecretVo> list = mapper.selectExchangeSecretPage(query);
        if (EmptyUtils.isNotEmpty(list)) {
            list.forEach(vo -> {
                String secret = vo.getSecret();
                //字符串每4位加个“-”
                String secretHasLine = secret.replaceAll("(.{4})", "$1-");
                //去掉最后一个“-”
                secretHasLine = secretHasLine.substring(0, secretHasLine.length() - 1);
                vo.setSecretHasLine(secretHasLine);
            });
        }
        PageInfo<ExchangeSecretVo> page = new PageInfo<ExchangeSecretVo>(list);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateBatchExchangeSecretByIds(ExchangeSecretDto dto) {
        //先看多选的ids里面是否有不属于可变更为该状态的数据
        String ids = dto.getIds();
        List<WelfareExchangeSecret> secretList = mapper.selectByIds(ids);
        Integer isActivate = dto.getIsActivate();
        //是否激活 0：未激活，1：激活，2：已冻结 ，3批量解冻
        //如果是批量激活
        if (isActivate == 1) {
            List<WelfareExchangeSecret> comp = secretList.stream().filter(x -> x.getIsActivate() != 0).collect(Collectors.toList());
            if(comp.size() > 0) {
                throw new CommonException("所选兑换券包含不能激活的兑换券，请重新选择！");
            }
            //生成业务员订单
            WelfareFeeOrder welfareFeeOrder = new WelfareFeeOrder();
            welfareFeeOrder.setEnterpriseId(dto.getEnterpriseId());
            welfareFeeOrder.setSalesUserId(dto.getSalesId());
            welfareFeeOrder.setCustomersId(dto.getCustomersId());
            welfareFeeOrder.setOrderType(2); //订单类型 1 福利卡 2 兑换券
            welfareFeeOrder.setExchangeId(secretList.get(0).getGroupId());
            welfareFeeOrder.setQuantity(secretList.size());
            welfareFeeOrder.setCreaterName(dto.getCreaterName());
            welfareFeeOrderService.insertSelective(welfareFeeOrder);
            Integer feeOrderId = welfareFeeOrder.getId();
            dto.setFeeOrderId(feeOrderId);
        }
        //如果是批量冻结
        if (isActivate == 2) {
            List<WelfareExchangeSecret> comp = secretList.stream().filter(x -> x.getIsActivate() != 1 && x.getIsActivate() != 3 && x.getIsActivate() != 4).collect(Collectors.toList());
            if(comp.size() > 0) {
                throw new CommonException("所选卡密包含不能冻结的卡密，请重新选择！");
            }
        }
        //如果是批量解冻
        if (isActivate == 3) {
            List<WelfareExchangeSecret> comp = secretList.stream().filter(x -> x.getIsActivate() != 2).collect(Collectors.toList());
            if(comp.size() > 0) {
                throw new CommonException("所选兑换券包含不能解冻的兑换券，请重新选择！");
            }
        }
        return mapper.updateBatchExchangeSecretByIds(dto);
    }

    @Override
    public WelfareExchangeWithSecretVo getExchangeInfoByExchangeSecretId(Integer exchangeSecretId) {
        return mapper.getExchangeInfoByExchangeSecretId(exchangeSecretId);
    }

    @Override
    public List<WelfareExchangeWithSecretVo> getUserExchangeBindList(Integer userId) {
        List<WelfareExchangeWithSecretVo> list = mapper.getUserExchangeBindList(userId);
        if(EmptyUtils.isNotEmpty(list)){
            list.forEach(x->{
                x.setIsExpired(CommonConstants.NO);
                x.setIsUsed(CommonConstants.NO);
                if(EmptyUtils.isNotEmpty(x.getExpiredDate()) && x.getExpiredDate().compareTo(new Date())==-1){
                    x.setIsExpired(CommonConstants.YES);
                }
                if(EmptyUtils.isNotEmpty(x.getUsedTime())){
                    x.setIsUsed(CommonConstants.YES);
                }
            });
        }
        return list;
    }

    @Override
    public List<ExchangeUserSecretVo> selectUserExchangeSecretVoListByUserId(Integer id) {
        return mapper.selectUserExchangeSecretVoListByUserId(id);
    }

    @Override
    public ExchangeSecretVo queryExchangeSecretByNumberOrSecret(String number, String secret) {
        if (EmptyUtils.isNotEmpty(secret)) {
            if (secret.length() == 19) {
                secret = secret.replaceAll("-", "");
            }
        }
        ExchangeSecretQuery query = new ExchangeSecretQuery();
        query.setNumber(number);
        query.setSecret(secret);
        List<ExchangeSecretVo> list = mapper.selectExchangeSecretPage(query);
        if (EmptyUtils.isEmpty(list)) {
            throw new CommonException("查无此券！");
        }
        ExchangeSecretVo vo = list.get(0);
        //字符串每4位加个“-”
        String secretHasLine = vo.getSecret().replaceAll("(.{4})", "$1-");
        //去掉最后一个“-”
        secretHasLine = secretHasLine.substring(0, secretHasLine.length() - 1);
        vo.setSecretHasLine(secretHasLine);
        return vo;
    }

    @Override
    public String confirmExchangeSecret(Integer userId, Integer exchangeSecretId){
        WelfareExchangeSecret welfareExchangeSecret = mapper.selectByPrimaryKey(exchangeSecretId);
        if(EmptyUtils.isEmpty(welfareExchangeSecret)){
            throw new CommonException("查无此券！");
        }
        if(welfareExchangeSecret.getIsActivate()==0){
            throw new CommonException("该券未激活！");
        }
        if(welfareExchangeSecret.getIsActivate()==2){
            throw new CommonException("该券已冻结！");
        }
        if(welfareExchangeSecret.getExpiredDate().compareTo(new Date())==-1){
            throw new CommonException("该券已过期！");
        }
        //判断该卡是否已兑换,若已兑换
        if(EmptyUtils.isNotEmpty(welfareExchangeSecret.getIsActivate()) && welfareExchangeSecret.getIsActivate()== WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_USED.getCode()){
            //若已绑定当前用户
            if(welfareExchangeSecret.getBindUserId().equals(userId)){
                //若已绑定当前用户，则返回订单id
                WelfareOrder query = new WelfareOrder();
                query.setExchangeSecretId(exchangeSecretId);
                query.setStatus(CommonConstants.YES);
                List<WelfareOrder> welfareOrders = welfareOrderService.select(query);
                if(EmptyUtils.isNotEmpty(welfareOrders)){
                    StringBuffer sb = new StringBuffer();
                    for (WelfareOrder order:welfareOrders) {
                        sb.append(order.getId()).append(",");
                    }
                    return sb.toString().substring(0,sb.length()-1);
                }
                return "0";
            }else{
                throw new CommonException("该卡已兑换过！");
            }
        }else{//若卡未兑换
            //若已绑定用户
            if(EmptyUtils.isNotEmpty(welfareExchangeSecret.getIsActivate()) && welfareExchangeSecret.getIsActivate()==WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_BOUND.getCode()){
                //若绑定是当前用户
                if(EmptyUtils.isNotEmpty(welfareExchangeSecret.getBindUserId()) && welfareExchangeSecret.getBindUserId().equals(userId)){
                    return "0";
                }else{
                    throw new CommonException("该卡已绑定其他用户！");
                }
            }else{
                //若未绑定，则绑定当前用户
                //welfareExchangeSecret.setIsBind(CommonConstants.YES);
                welfareExchangeSecret.setBindTime(new Date());
                welfareExchangeSecret.setBindUserId(userId);
                welfareExchangeSecret.setUpdateTime(new Date());
                welfareExchangeSecret.setIsActivate(WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_BOUND.getCode());
                mapper.updateByPrimaryKeySelective(welfareExchangeSecret);
                return "0";
            }
        }
    }

    @Override
    public Integer selectCountYearExchange(String s) {
        return mapper.selectCountYearExchange(s);
    }

    @Override
    public List<WelfareFeeUserSales> selectSalesByExchangeId(WelfareSalesCustomersQuery query) {
        return mapper.selectSalesByExchangeId(query);
    }

    @Override
    public List<WelfareFeeUserCustomers> selectCustomersByExchangeId(WelfareSalesCustomersQuery query) {
        return mapper.selectCustomersByExchangeId(query);
    }

}
